package com.example.photo_sharing.tool.Impl;

import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.FileUtils;
import android.os.NetworkOnMainThreadException;
import android.webkit.MimeTypeMap;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.photo_sharing.global.App;
import com.example.photo_sharing.tool.photoTool;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PhotoImpl implements photoTool {

    private App app = new App();
    private ArrayList<String> pictures = new ArrayList<>();
    private String imageCode;
    Context context;

    //头像
    @Override
    public String uploadAvatar(Uri uri,Context context){
        this.context = context;
        ArrayList<Uri> uris = new ArrayList<>();
        uris.add(uri);
        ArrayList<String> res = uploadPic(uris);
        app.setDelay(300);
        return pictures.get(0);
    }

    //组图
    @Override
    public String uploadPhotos(List<File> files) {
        post(files);
        return imageCode;
    }

    //图片 uri转bitmap
    @Override
    public Bitmap getBitmapFromUri(Uri uri) throws FileNotFoundException {
        Bitmap bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri));
        return bitmap;
    }

    //上传图片的实现
    private ArrayList<String> uploadPic(ArrayList<Uri> uris){
        List<File> pics = new ArrayList<>();
        //将传入的Uri转为File
        for (int i = 0;i<uris.size();i++){
            System.out.println("123123123123123"+uris.get(0).getPath());
            File file = uriToFileApiQ(uris.get(0),context);
            pics.add(file);
        }
        post(pics);
        return pictures;
    }

    //上传文件的接口
    private void post(List<File> pics){
        new Thread(() -> {

            // url路径
            String url = "http://47.107.52.7:88/member/photo/image/upload";

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("Accept", "application/json, text/plain, */*")
                    .add("appId", app.getAppId())
                    .add("appSecret", app.getAppSecret())
                    .add("Content-Type", "multipart/form-data")
                    .build();

            // 请求体
            MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM);
                    for(int i=0 ;i<pics.size();i++){
                        builder.addFormDataPart("fileList", pics.get(i).getName(),RequestBody.create(MediaType.parse("multipart/form-data"), pics.get(i)));
                    }
            MultipartBody build = builder.build();
            //MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .post(build)
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    /**
     * 回调
     */
    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            String responseData = response.body().string();
            System.out.println(responseData);
            //将结果中的字符串数组作为
            JSONObject jsonObject  = JSONObject.parseObject(responseData).getObject("data", JSONObject.class);
            JSONArray jsonArray = jsonObject.getJSONArray("imageUrlList");
            imageCode = jsonObject.getString("imageCode");
            System.out.println("------------------------"+imageCode);
            pictures = (ArrayList<String>) JSON.parseArray(jsonArray.toString(),String.class);
            System.out.println("------------------------"+pictures.get(0));
        }
    };

    public File uriToFileApiQ(Uri uri, Context context) {
        File file = null;
        if(uri == null) return file;
        //android10以上转换
        if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
            file = new File(uri.getPath());
        } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            //把文件复制到沙盒目录
            ContentResolver contentResolver = context.getContentResolver();
            String displayName = System.currentTimeMillis()+ Math.round((Math.random() + 1) * 1000)
                    +"."+ MimeTypeMap.getSingleton().getExtensionFromMimeType(contentResolver.getType(uri));

//            注释掉的方法可以获取到原文件的文件名，但是比较耗时
//            Cursor cursor = contentResolver.query(uri, null, null, null, null);
//            if (cursor.moveToFirst()) {
//                String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));}

            try {
                InputStream is = contentResolver.openInputStream(uri);
                File cache = new File(context.getCacheDir().getAbsolutePath(), displayName);
                FileOutputStream fos = new FileOutputStream(cache);
                FileUtils.copy(is, fos);
                file = cache;
                fos.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 将图片转为file
     *
     * @param url 图片url
     * @return File
     * @author dyc
     * date:   2020/9/4 14:54
     */
    public File getFile(String url) throws Exception {
        //对本地文件命名
        String fileName = url.substring(url.lastIndexOf("."),url.length());
        File file = null;

        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("net_url", fileName);
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return file;
    }


    public String getImageCode() {
        return imageCode;
    }
}
